package com.basker.pisces.domain.command.exception;

import java.util.Arrays;
import java.util.List;

import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import com.basker.pisces.domain.constant.DomainConstants;
import com.basker.pisces.resource.StringResources;
import com.basker.pisces.service.exception.IObjectErrorsWrapper;

/**
 * 非法数据对象异常,命令执行过程中，未通过校验环节会产生此异常
 *
 * @author hangwen
 */
public class CommandExecuteInvalidObjectException extends CommandExecuteRuntimeException
        implements IObjectErrorsWrapper {

    private static final long serialVersionUID = 3634976463670725481L;

    private List<ObjectError> errors;

    public CommandExecuteInvalidObjectException(List<ObjectError> errors) {
        this(StringResources.get("pisces-domain.CommandExecuteInvalidObjectException.message"), errors);
    }

    protected CommandExecuteInvalidObjectException(String message) {
        super(message);
    }

    protected CommandExecuteInvalidObjectException(String message, List<ObjectError> errors) {
        super(message);
        this.errors = errors;
    }

    protected CommandExecuteInvalidObjectException(String message, ObjectError error) {
        this(message, Arrays.asList(error));
    }

    @Override
    public List<ObjectError> getErrors() {
        return errors;
    }

    @Override
    public String getMessage() {
        String message = super.getMessage();

        if (!CollectionUtils.isEmpty(errors)) {
            message = getObjectErrorsMessage(message, errors);
        }

        return message;
    }

    @Override
    public int getStatus() {
        return DomainConstants.StatusCode.INVALID_OBJECT_VIOLATION;
    }

    private String getObjectErrorsMessage(String message, List<ObjectError> errors) {
        String joinedMessage = ObjectError.joinErrorMessage(errors);
        return !StringUtils.isEmpty(joinedMessage) ? message + joinedMessage : message;
    }

}
